package com.sbtr.common.file.impl;

import com.sbtr.common.file.FileService;
import com.sbtr.common.file.dto.FileDto;
import com.sbtr.common.file.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Component
public class FileServiceImpl implements FileService {

    @Value("${oss.config.uploadPath}")
    private String uploadPath;

    @Value("${oss.config.samplePath}")
    private String samplePath;

    @Override
    public <T extends FileDto> T uploadFile(MultipartFile file, T dto) {
        if (file.isEmpty() || file.getSize() == 0) {
            throw new IllegalArgumentException("上传文件为空！！");
        }
        if (StringUtils.isBlank(dto.getModel())) {
            throw new IllegalArgumentException("上传模块类型为空！！");
        }

        String fileName = file.getOriginalFilename();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + fileName.substring(fileName.lastIndexOf("."));

        String bucketDir;
        if (StringUtils.isNotBlank(dto.getPathType()) && dto.getPathType().equals("sample")) {
            bucketDir = samplePath + "/" + dto.getModel();
        } else {
            bucketDir = uploadPath + "/" + dto.getModel();
        }

//        String filePath = bucketDir +"/" + otherName;

        if (fileName.toLowerCase().endsWith(".txt") || fileName.toLowerCase().endsWith(".csv")) {
            OutputStreamWriter os = null;
            InputStreamReader inputStream = null;
            try {
                String encode = FileUtil.getEncode(file);
                inputStream = new InputStreamReader(file.getInputStream(), encode);
                // 2、保存到临时文件
                // 1K的数据缓冲
                char[] bs = new char[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流保存到本地文件
                File tempFile = new File(bucketDir);
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                os = new OutputStreamWriter(new FileOutputStream(tempFile.getPath() + "/" + otherName), StandardCharsets.UTF_8);
                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 完毕，关闭所有链接
                try {
                    os.flush();
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            OutputStream os = null;
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                // 2、保存到临时文件
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流保存到本地文件
                File tempFile = new File(bucketDir);
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                os = new FileOutputStream(tempFile.getPath() + "/" + otherName);
                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 完毕，关闭所有链接
                try {
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        dto.setPath(bucketDir + "/" + otherName);
        dto.setBucketDir(bucketDir);
        dto.setFileName(file.getOriginalFilename());
        dto.setFileName2(otherName);
        dto.setFileSize(Long.toString(file.getSize()));
        return dto;
    }

    @Override
    public <T extends FileDto> T uploadFile(File file, T dto) {
        if (file.exists()) {
            throw new IllegalArgumentException("上传文件为空！！");
        }
        if (StringUtils.isBlank(dto.getModel())) {
            throw new IllegalArgumentException("上传模块类型为空！！");
        }

        String fileName = file.getName();
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + fileName.substring(fileName.lastIndexOf("."));

        String bucketDir;
        if (StringUtils.isNotBlank(dto.getPathType()) && dto.getPathType().equals("sample")) {
            bucketDir = samplePath + "/" + dto.getModel();
        } else {
            bucketDir = uploadPath + "/" + dto.getModel();
        }
        OutputStream os = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(bucketDir);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + "/" + otherName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        dto.setPath(bucketDir + "/" + otherName);
        dto.setBucketDir(bucketDir);
        dto.setFileName(file.getName());
        dto.setFileName2(otherName);
        dto.setFileSize(Long.toString(file.length()));
        return dto;
    }

    @Override
    public void downloadFile(HttpServletResponse resp, String path, String name) {
        OutputStream out = null;
        // 读取本地文件的输入流
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            // 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment;" + " filename=" + name);
            // 把本地文件发送给客户端
            out = resp.getOutputStream();
            int byteRead = 0;
            byte[] buffer = new byte[512];
            while ((byteRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
